from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from constr_budgets.models import *
import json
from utils.Infinite2 import infinite2 as data1
import datetime
from django.db import connection
import time


# Create your place here.

class RecoderView(View):
    def get(self, request):

        day_id = request.GET.get("day_id", "")

        try:
            project_id = request.GET.get("project_id")
            template_id = Project.objects.get(id=project_id).templates_id
        except:
            return JsonResponse({"code": 406, "message": "目标工程不存在", "placelist": [], "moduleslist": []})

        aimTemplate = Templates.objects.get(id=template_id)
        placelist = list(aimTemplate.place_set.all().values())
        moduleslist = list(aimTemplate.modules_set.all().values())

        try:
            aimpeople_id = request.GET.get("people_id", '')
            if aimpeople_id:
                project_id = request.GET.get("project_id")
                aimpeople = People.objects.get(id=aimpeople_id)
                templist = aimpeople.role_auth
                templist = eval(templist)[int(project_id)]
                moduleslist = list(Modules.objects.filter(id__in=templist).values())
                day_id = datetime.datetime.now().strftime("%Y-%m-%d")

                # print(moduleslist)
            # modules_id_list = json.loads(request.GET.get("modules_id_list","[]"))
            # if len(modules_id_list):
            #     moduleslist = list(aimTemplate.modules_set.filter(id__in=modules_id_list).values())
        except:
            return JsonResponse({"code": 406, "message": "权限ID列表不符条件"})

        resultlist = []
        timelist = []  # 记录多条时间id
        aimdata = ""

        try:
            start_day = request.GET.get("start_day", "2020-01-01")
            if not start_day:
                start_day = "2020-01-01"
            start_day = datetime.datetime.strptime(start_day, "%Y-%m-%d").date()
            end_day = request.GET.get("end_day", "2622-01-01")
            if not end_day:
                end_day = "2622-01-01"
            end_day = datetime.datetime.strptime(end_day, "%Y-%m-%d").date()
            dayList = Day.objects.all().values()
            # print(start_day)
            # print(end_day)

            for i in list(dayList):
                if start_day <= i["time"] <= end_day:
                    aimProject = Project.objects.get(id=project_id)
                    if i["time"]>=aimProject.createTime:
                        timelist.append(i['id'])
            if start_day == end_day:
                aimdata = Day.objects.get(time=start_day)
            # print(timelist)
            # print(888888888888)
        except:
            print("nonono")
            pass

        # aimProject = Project.objects.get(id=project_id)
        # tlist = Day.objects.filter(time__gte=aimProject.createTime)     #该项目所投入使用的所有时间

        # print(timelist)
        remarkList = []

        # all_time_list = Day.objects.filter(time__gte=aimProject.createTime)     #项目运转时间
        # print(all_time_list)


        for i in moduleslist:
            temp = []
            totalmoney = 0
            totalnum = 0
            for j in placelist:

                # for t in tlist:
                # if not Record.objects.filter(modules = i['id']).filter(place=j['id']).filter(project_id=project_id).filter(day_id=t.id):
                #     newRecoder =Record.objects.create(project_id=project_id,day_id=t.id)
                #     newRecoder.modules.add(i['id'])
                #     newRecoder.place.add(j['id'])
                # print(len(timelist))
                # print(timelist)
                try:
                    if day_id.isdigit():
                        res = list(
                            Record.objects.filter(modules=i['id']).filter(place=j['id']).filter(day_id=day_id).filter(
                                project_id=project_id).values())
                        # count = cur.execute("select * from constr_budgets_record where modules = i['id'] and place=j['id'] and day_id = day_id and project_id=project_id ")
                        data = {}  # 放止无效的数据
                        if (len(res)):
                            data = res[0]

                    elif len(timelist) > 0:
                        # res = list(Record.objects.filter(modules=i['id']).filter(place=j['id']).filter(day_id__in=timelist).filter(project_id=project_id).values())
                        data = {}  # 放止无效的数据
                        cur = connection.cursor()
                        # count = cur.execute(
                        #     "select A.* from constr_budgets_record as A  join constr_budgets_record_modules as AB on A.id = AB.record_id join modules as B on B.id = AB.modules_id  join constr_budgets_record_place as AC on A.id = AC.record_id  join place as C on C.id = AC.place_id where AB.modules_id = " + str(
                        #         i['id']) + " and AC.place_id = " + str(j['id']) + " and A.project_id= " + str(
                        #         project_id) + " and A.day_id in " + str(timelist).replace('[', '(').replace(']', ')')
                        # )

                        count = cur.execute(
                            "select A.* from constr_budgets_record as A  join constr_budgets_record_modules as AB on A.id = AB.record_id join modules as B on B.id = AB.modules_id  join constr_budgets_record_place as AC on A.id = AC.record_id  join place as C on C.id = AC.place_id where AB.modules_id = " + str(
                                i['id']) + " and AC.place_id = " + str(j['id']) + " and A.project_id= " + str(
                                project_id))

                        res = cur.fetchall()
                        if (len(res)):
                            for item in res:
                                if item[1]:
                                    totalmoney+=item[1]
                                if item[2]:
                                    totalnum+=item[2]

                                if item[3] in timelist:

                                    if data == {}:
                                        data = {'id': item[0], 'money': item[1], 'num': item[2], day_id: item[3],
                                                project_id: item[4]}
                                        if not data['num']:
                                            data['num'] = 0
                                        if not data['money']:
                                            data['money'] = 0
                                    else:
                                        if item[2]:
                                            data['num'] += item[2]
                                        if item[1]:
                                            data['money'] += item[1]


                    elif timelist == []:
                        return JsonResponse({"code": 200, "placelist": placelist, "moduleslist": []})
                    else:
                        res = list(Record.objects.filter(modules=i['id']).filter(place=j['id']).filter(
                            project_id=project_id).values())
                        # count = cur.execute(
                        #     "select * from constr_budgets_record as A,modules as B,place as C, constr_budgets_record_modules as AB, constr_budgets_record_place as AC  where B.id = i['id'] and AB.modules_id = i['id'] and C.id = j['id'] and AC.place_id = j['id'] and A.project_id=project_id ")


                        data = {}  # 放止无效的数据
                        if (len(res)):

                            for item in res:
                                if item['money']:
                                    totalmoney+=item['money']
                                if item['num']:
                                    totalnum+=item['num']

                                if data == {}:
                                    data = item
                                    if not data['num']:
                                        data['num'] = 0
                                    if not data['money']:
                                        data['money'] = 0
                                else:
                                    if item['num']:
                                        data['num'] += item['num']
                                    if item['money']:
                                        data['money'] += item['money']
                except:
                    return JsonResponse({"code": 406, "message": "时间数据有误"})
                temp.append(data)
            i["maindata"] = temp
            i['totalnum'] = totalnum
            i['totalmoney'] = totalmoney
            print(totalnum)
            if aimdata:
                # i["remarks"] = Remarks.objects.filter(day_id=aimdata.id).filter(modules_id=i['id'])
                if list(Remarks.objects.filter(day_id=aimdata.id).filter(modules_id=i['id']).filter(
                        project_id=project_id).values()):
                    i["remarks"] = list(Remarks.objects.filter(day_id=aimdata.id).filter(modules_id=i['id']).filter(
                        project_id=project_id).values())[0]
                else:
                    i["remarks"] = [{}]
            resultlist.append(i)

        moduleslist = data1(resultlist)
        # print(moduleslist)
        return JsonResponse({"code": 200, "placelist": placelist, "moduleslist": moduleslist})

    def put(self, request):
        data = json.loads(request.body)
        if not str(data['money']).isdigit() or not str(data['num']).isdigit():
            return JsonResponse({"code": 500, "message": "提示:请填写数字~"})
        id = data['id']
        data.pop("id")
        temp = {}
        for i in data:
            if i in ["money", "num", "day_id"]:
                temp[i] = data[i]
        oldRecord = Record.objects.get(id=id)
        Record.objects.filter(id=id).update(**temp)
        aimRecord = Record.objects.get(id=id)
        project_id = aimRecord.project_id
        aimModule = Modules.objects.get(id=aimRecord.modules.all()[0].id)
        if not aimModule.is_materials:
            return JsonResponse({"code": 200, "message": "修改成功"})
        if len(Materials.objects.filter(project_id=project_id,modules_id=aimModule.id).values()):
            if oldRecord.money == aimRecord.money and oldRecord.num == aimRecord.num:
                print("忽略")
            else:
                if not oldRecord.num:
                    oldNum = 0
                else:
                    oldNum = oldRecord.num
                if not oldRecord.money:
                    oldMoney = 0

                else:
                    oldMoney = oldRecord.money
                aimMaterials = Materials.objects.filter(project_id=project_id,modules_id=aimModule.id).values()[0]
                totalHistory = MaterialsHistory.objects.create(project_id=project_id,materials_id=aimMaterials['id'],change_num=-float(temp['num'])+float(oldNum),change_price=-float(temp['money'])+float(oldMoney))
                #修改过去的数据时所产生的出库记录
                if oldRecord.day_id != Day.objects.get(time=datetime.datetime.now().strftime("%Y-%m-%d")).id:
                    print(Day.objects.get(id=oldRecord.day_id).time)
                    totalHistory.add_time = Day.objects.get(id=oldRecord.day_id).time
                    totalHistory.save()

                aimMaterials = Materials.objects.get(project_id=project_id,modules_id=aimModule.id)
                aimMaterials.materials_num += float(totalHistory.change_num)
                aimMaterials.materials_price += float(totalHistory.change_price)
                aimMaterials.save()
        else:
            Materials.objects.create(project_id=project_id,modules_id=aimModule.id,materials_num=-int(temp['num']),materials_price=-int(temp['money']))



        # aimModule = Modules.objects.get(id=aimRecord.modules.all()[0].id)
        # project_id = aimRecord.project_id
        # print(aimModule.id)
        # print(Materials.objects.filter(modules_id=aimModule.id))
        # MaterialsHistory.objects.create(project_id=project_id,materials_id=Materials.objects.get(modules_id=aimModule.id).id,change_num=aimModule.num,change_money=aimModule.money)
        return JsonResponse({"code": 200, "message": "修改成功"})
